#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:taotieren

"""
    rpi.gpio 需要 root 权限，板上运行需要使用
    sudo python gui_sensor_reading.py
    显示传感器的值
    使用 SR-04 读取测距
       SR-04 测距传感器，1 个 470Ω 电阻，1 个 270Ω 电阻
        5V ---------- SR-04_Pin1 (VCC)
        18 ---------- SR-04_Pin2 (Trigger)
        23 ---270---- SR-04_Pin3 (Echo）
             |
             |
            470
             |
             |
        GND ---------- SR-04_Pin4 (GND)
    为了将测距传感器回波输出从 5V 降到 3.3V 电阻是必不可少的
    这种测距方法不是十分准确，因为温度、压力和相对湿度都会影响音速，从而影响距离读数的准确性。
    增加 Tkinker 显示

"""

""" 非树莓派环境下可以用 rpi.gpio_def 代替 rpi.gpio 来进行程序调试和验证 """

import RPi.GPIO as GPIO
import time

""" python3 中请安装 tkintertoy 来进行程序调试和验证 """
from tkinter import *

trigger_pin = 18
echo_pin = 23

GPIO.setmode(GPIO.BCM)
GPIO.setup(trigger_pin, GPIO.OUT)
GPIO.setup(echo_pin, GPIO.IN)


def send_trigger_pulse():
    GPIO.output(trigger_pin, True)
    time.sleep(0.0001)
    GPIO.output(trigger_pin, False)


def wait_for_echo(value, timeout):
    count = timeout
    while GPIO.input(echo_pin) != value and count > 0:
        count = count - 1


def get_distance():
    send_trigger_pulse()
    wait_for_echo(True, 10000)
    start = time.time()
    wait_for_echo(False, 10000)
    finish = time.time()
    pulse_len = finish - start
    distance_cm = pulse_len / 0.000058
    distance_in = distance_cm / 2.5
    return (distance_cm, distance_in)


class App:
    def __init__(self, master):
        self.master = master
        frame = Frame(master)
        frame.pack()
        lable = Label(frame, text='Distance (inches)', font=("Hack", 32))
        lable.grid(row=0)
        self.reading_label = Label(frame, text='12.34', font=("Hack", 110))
        self.reading_label.grid(row=1)
        self.update_reading()

    def update_reading(self):
        cm, inch = get_distance()
        reading_str = "{:.2f}".format(inch)
        self.reading_label.configure(text=reading_str)
        self.master.after(500, self.update_reading)


root = Tk()
root.wm_title('Range Finder')
app = App(root)
root.geometry("400x300+0+0")
root.mainloop()
